home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11144 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: news2.noc.netcom.net!news
  2. From: Tarang Deshpande <tarang@willows.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: REQUEST: Recursive functions
  5. Date: Wed, 20 Mar 1996 08:33:15 -0800
  6. Organization: NETCOM Network Operations
  7. Message-ID: <3150334B.1802@willows.com>
  8. References: <4h7lft$8ql@cis.clark.edu>
  9. NNTP-Posting-Host: daffy.willows.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0GoldB1 (Win95; I)
  14.  
  15. Michael Talmage wrote:
  16. > I need some help to write a recursive function that will move a mouse through
  17. > a maze to find some cheese at the end.  My instructor did not really teach us
  18. > how to write recursive functions in class.  Any help will be appreciated.
  19.  
  20. I'm not going to tell you the answer but here is a quick leson in
  21. recursion.  First of all anything you do recursively can be done 
  22. using loops.  But using loops is more complicated and cumbersome whereas
  23. recursion is more elegant and simple.  However this does not mean that
  24. you should always use recusion because recursion make heavy use of the
  25. stack and this can cause you to run out of memory.
  26.  
  27. What recusion does is to divide the problem into two or more parts.
  28. Each part is still the same problem and hence you can apply the same
  29. solution to each of the parts; to divide them yet again, and so on.
  30. Finally you have divided the problem down to a part for which the
  31. answer is simple.  Then all you have to do is to is to combine the
  32. simple answers for each of the parts you have divide the problem into.
  33.  
  34. For example, the clasic example, the problem of factorials.
  35.  
  36. f(x) = x * (x-1) * (x-2) * ... * 1
  37.  
  38. A standard loop soulution to the problem would be:
  39.  
  40. for ( f = x--; x; x-- )
  41.     f *= x;
  42.  
  43. whereas the recusive solution would be:
  44.  
  45. if ( x <= 1 )
  46.     return ( 1 );
  47. else
  48.     return ( x * factorial ( x - 1 ) );
  49.  
  50. Hope that helps.
  51.